<template>
  <div>
    <el-page-header @back="goBack" content="书本详情"></el-page-header>
    <div class="background-container">
      <img class="book-image" :src="bookInfo.picture">
      <div class="book-details">
        <h2 class="book-name">{{ bookInfo.name }}</h2>
        <p class="book-author">作者: {{ bookInfo.author }}</p>
        <p class="book-language">语言: {{ bookInfo.language }}</p>
        <p class="book-typeId">类型名称: {{ typeNamesMap[bookInfo.typeId] }}</p>
        <p class="book-publisher">出版社: {{ bookInfo.publish }}</p>
        <p class="book-publishDate">上架时间: {{ bookInfo.publishDate|formatter }}</p>
        <div class="action-buttons">

          <el-button v-if="isCollect" @click="changeCollect" type="primary" icon="el-icon-star-on">已收藏</el-button>
          <el-button v-else @click="changeCollect" type="primary" icon="el-icon-star-off">收藏</el-button>

          <el-button v-if="lendForm.backtype === 0" type="success"icon="el-icon-date">在借中</el-button>
          <el-button v-else @click="dialogVisible = true" type="success"icon="el-icon-s-management">借阅</el-button>
        </div>
      </div>
    </div>
    <div class="book-description">
      <el-tabs v-model="activeName">
      <el-tab-pane label="简介" name="first">{{ bookInfo.introduction }}</el-tab-pane>
      <el-tab-pane label="评论" name="second"><BookInfoComment :id="bookInfo.id"></BookInfoComment></el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog
        title="借阅"
        :visible.sync="dialogVisible"
        width="50%"
        center
        :before-close="handleClose">

      <el-form :model="readerForm" :rules="rules" ref="readerForm">
        <el-form-item label="借书卡号" :label-width="formLabelWidth" prop="readernumber">
          <el-input v-model="readerForm.readernumber" prefix-icon="el-icon-reading" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="readerForm.password" show-password prefix-icon="el-icon-lock"  size="small" ></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="tel">
          <el-input v-model="readerForm.tel" prefix-icon="el-icon-mobile-phone" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleConfirm" plain>确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import BookInfoComment from "@/views/reader/BookInfoComment.vue";
export default {
  name: "BookDetail",
  components: {BookInfoComment},

  data(){
    return {
      formLabelWidth: '90px',
      dialogVisible: false,
      options: [],
      typeNamesMap: {},
      readerForm:{
        readernumber: '',
        tel: '',
        password:''
      },
      lendForm:{
        readernumber:'',
        name:'',
        bookid:'',
        readerid:'',
        lenddate:'',
        backdate:'',
        backtype:'',
        exceptremarks:''
      },
      readerid:sessionStorage.getItem("id"),
      bookid:this.$route.query.id,
      isCollect: false,
      isBorrow: false,
      count:0,
      bookInfo:{},
      activeName: 'second',
      rules: {
        readernumber: [
          { required: true, message: '请输入借书卡号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        tel: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
        ]
      }
    }
  },
  mounted(){
    console.log(this.$route.query.id)
    this.getBookInfoById()
    this.getCollect()
    this.countCollect()
    this.getBorrowStatus()
    this.fetchTypeNames()
  },
  methods: {
    async countCollect() { // 获取书本被收藏数量
      const { data: res } = await this.$axios.get("/collect/countCollect", { params: { bookid: this.$route.query.id } })
      console.log(res.data)
      this.count = res.data
    },
    // 获取收藏的状态
    async getCollect() {
      const { data: res } = await this.$axios.get("/collect/getCollect", {
        params: {
          bookid: this.$route.query.id,
          readerid: sessionStorage.getItem("id")
        }
      })
      if (res.data) {
        this.isCollect = true // 此书本已被当前用户收藏
      } else {
        this.isCollect = false // 确保在未收藏时设置为 false
      }
    },
    // 切换收藏的状态
    async changeCollect() {
      this.isCollect = !this.isCollect
      const { data: res } = await this.$axios.get("/collect/changeCollect", {
        params: {
          bookid: this.$route.query.id,
          readerid: sessionStorage.getItem("id")
        }
      })
      if (res.data) {
        this.$message.info("取消收藏")
      } else {
        this.$message.success("收藏成功")
      }
      await this.countCollect()
    },
    handleConfirm() {
      this.$refs.readerForm.validate(async (valid) => {
        if (valid) {
          try {
            const { data: res } = await this.$axios.get("reader/validateReaderWriteInfo", {
              params: {
                id: sessionStorage.getItem("id"),
                password: this.readerForm.password,
                readernumber: this.readerForm.readernumber,
                tel: this.readerForm.tel
              }
            });

            if (res.success) {
              // 验证成功，调用借阅方法
              await this.changeBorrow();
              this.dialogVisible = false;
            } else {
              this.$message.error("输入信息错误");
            }
          } catch (error) {
            console.error("验证失败", error);
            this.$message.error("验证失败，请重试");
          }
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    async changeBorrow() {
      this.isBorrow = !this.isBorrow
      this.lendForm.lenddate=this.getCurrentDate()
      this.lendForm.backtype = 0;
      this.lendForm.readerid = sessionStorage.getItem("id")
      this.lendForm.bookid = this.$route.query.id
      const {data: res} = await this.$axios.post("lendList/addReaderLendList",this.lendForm)
      if (res.data) {
        this.$message.success("借阅成功")
      }
      await this.getBorrowStatus()
    },
    async getBookInfoById() {
      const { data: res } = await this.$axios.get('/bookInfo/getLibraryInfoById', {
        params: {
          id: this.$route.query.id
        }
      })
      if (res.data) {
        this.bookInfo = res.data
      }
    },
    async fetchTypeNames() {
      const { data: res } = await this.$axios.get("typeInfo/getAllTypeNames");
      this.options = res.data.map(type => ({
        value: type.id,
        label: type.name
      }));
      this.typeNamesMap = res.data.reduce((map, type) => {
        map[type.id] = type.name;
        return map;
      }, {});
    },
    getCurrentDate() {
      const now = new Date();
      return now.toISOString();
    },
    goBack() {
      this.$router.go(-1)
    },
    async getBorrowStatus() {
      const { data: res } = await this.$axios.get("/lendList/getBorrowStatus", {
        params: {
          bookid: this.$route.query.id,
          readerid: sessionStorage.getItem("id")
        }
      })
      if (res.data) {
        this.isBorrow = true // 用户已借阅
        this.lendForm.backtype = res.data.backtype;
      } else {
        this.isBorrow = false // 用户未借阅
      }
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    }
  },
  filters:{
    formatter(date){
      return new Date(date).toLocaleDateString()
    }
  }
}
</script>

<style scoped>
.background-container {
  background: url(@/assets/bg.png) no-repeat center center;
  background-size: cover;
  height: 300px;
  width: 100%;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.book-image {
  width: 250px;
  height: 280px;
  position: absolute;
  top:55px; /* 调整顶部位置 */
  left: 15%; /* 调整左侧位置 */
  border: 3px solid black;
  object-fit: cover;
}
.book-details {
  /*margin-left: -22%;*/
  margin-top:3%;
  color: white; /* 根据背景图颜色调整文字颜色 */

}

.book-name {
  font-size: 24px;
  margin: 0;
}

.book-author,
.book-publisher,
.book-language,
.book-typeId {
  font-size: 16px;
  margin: 5px 0;
}
.action-buttons{
  margin-left: 0;
  margin-top:15%;
}
.book-description{
  width: 70%;
  margin: 0px auto ; /* 使内容居中 */
  padding-top: 50px;
}

.el-main {
  background-color:white;
}



</style>